import { defineStore } from 'pinia'
import { ref } from 'vue'
import { getLoginUserUsingGet, userLogoutUsingPost } from '@/api/userController.ts'
import { getToken, removeToken, setToken } from '@/utils/auth.ts'
import { message } from 'ant-design-vue'
import router from '@/router'

/**
 * 存储登录用户信息的状态
 */
export const useLoginUserStore = defineStore('loginUser', () => {
  const loginUser = ref<API.LoginUserVO>({
    userName: '未登录',
  })

  /**
   * 获取登录用户信息
   */
  async function fetchLoginUser() {
    const res = await getLoginUserUsingGet()
    if (res.data.code === 0 && res.data.data) {
      // 设置登录用户信息
      loginUser.value = res.data.data
    }
  }

  /**
   * 退出登录
   */
  async function userLogout() {
    const res = await userLogoutUsingPost()
    if (res.data.code === 0) {
      setLoginUser({
        userName: '未登录',
      })
      message.success('退出登录成功')
      removeToken()
      await router.push('/user/login')
    } else {
      message.error('退出登录失败 ' + res.data.message)
    }
  }

  /**
   * 设置登录用户
   * @param newLoginUser
   */
  function setLoginUser(newLoginUser: any) {
    loginUser.value = newLoginUser
  }

  return { loginUser, setLoginUser, fetchLoginUser, userLogout }
})
